<?
include_once("ANotify.class.php");
class WFile extends ANotify
{
	private $Notify;
	function WFile($Notify=true)
	{
		$this->Notify	= $Notify;
	}
	function write_to_file ($filename, $data, $method = "w")
	{
		$message	= "";
		$filename	= mb_convert_encoding($filename,SYSTEM_CODE,WEB_CODE);
		if(strlen($data) == 0)
			return;
		if(file_exists($filename))
		{
			if($method=="w")
				unlink($filename);
			else 
			{
				$message	= "$filename 文件已经存在，且不允许覆盖！";
				if($this->Notify)
					$this->halt($message);
				else 
					throw  new Exception($message);
			}
		}
			//$fp = fopen($filename, $method);
		//else
		$fp	= fopen($filename, "x");
		if(!$fp)
		{
			$message	= "打开文件 $filename 失败！";
			if($this->Notify)
				$this->halt($message);
			else 
				throw  new Exception($message);
		}
		flock($fp, LOCK_EX);
		if(!@fwrite($fp, $data))
		{
			flock($fp, LOCK_UN);
			fclose($fp);
			$message	= "向文件 $filename 写入数据失败！";
			if($this->Notify)
				$this->halt($message);
			else 
				throw  new Exception($message);
		}
		flock($fp, LOCK_UN);
		fclose($fp);
	}
	function getfile($url)
	{
		$message	= "";
		$str = "";
		$url		= mb_convert_encoding($url,SYSTEM_CODE,WEB_CODE);
		if(($handle = fopen($url, "r"))==true)
		{
			while (!feof($handle)) {
				$str .= fread($handle, 8192);
			}
			fclose($handle);
		}
		else
		{
			if($this->Notify)
				$this->halt("$url 文件不存在");
			else 
				throw  new Exception($message);
		}
		return $str;
	}
	function DeleteTree($filename)
	{
		if(is_file($filename))
			unlink($filename);
		else
		{
			$handle = opendir($filename);
			while(false !== ($file = readdir($handle))) 
			{
				if($file != "." && $file != "..")
				{
					$file	= mb_convert_encoding($file,SYSTEM_CODE,WEB_CODE);
					$this->DeleteTree("$filename/$file");
				}
			}
			rmdir($filename);
		}
		return true;
	}
	function CreateDir($dir,$root=DOCUMENTROOT)
	{
		if($dir == "")
		{
			print($dir);exit;
			throw new Exception("需要创建目录为空！");
		}
		$dir	= str_replace("\\","/",$dir);
		$dir	= trim($dir,"/");
		$arr	= explode("/",$dir);
		$len	= count($arr);
		for($i=0;$i<$len;$i++)
		{
			$root	= "$root/{$arr[$i]}";
			if(!file_exists($root))
			{
				if(!mkdir($root))
					throw new Exception("创建目录 $root 失败！");
			}
		}
	}
}
?>